<script lang="ts" setup>
import { createRole, CreateRoleParams } from "@/api/modules/system";
import { message } from "@/utils/message";
import { cloneDeep } from "@pureadmin/utils";
import type { PlusColumn } from "plus-pro-components";
import { PlusDrawerForm } from "plus-pro-components";
import "plus-pro-components/es/components/drawer-form/style/css";
import { ref } from "vue";

// 定义 emit 事件，用于通知父组件刷新数据
const emit = defineEmits(["refresh"]);

const rules = {
  name: [
    {
      required: true,
      message: "请输入角色名称"
    }
  ],
  code: [
    {
      required: true,
      message: "请输入角色编码"
    }
  ]
};

const state = ref<CreateRoleParams>({
  name: "",
  code: "",
  description: "",
  status: 1
});
const initState = cloneDeep(state.value);

const columns: PlusColumn[] = [
  {
    label: "角色名称",
    prop: "name",
    valueType: "copy"
  },
  {
    label: "角色编码",
    prop: "code",
    valueType: "copy"
  },
  {
    label: "角色描述",
    prop: "description",
    valueType: "textarea"
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "启用",
        value: 1
      },
      {
        label: "禁用",
        value: 0
      }
    ]
  }
];

const visible = ref(false);

const handleOpen = () => {
  visible.value = true;
};

const handleCancel = () => {
  visible.value = false;
  state.value = cloneDeep(initState);
};

const handleConfirm = async () => {
  await createRole(state.value).then(res => {
    if (res.success) {
      message("创建成功", { type: "success" });
      // 触发 refresh 事件，通知父组件刷新表格数据
      emit("refresh");
      handleCancel();
    }
  });
};
</script>

<template>
  <el-button type="primary" @click="handleOpen"> 创建新角色 </el-button>
  <PlusDrawerForm
    v-if="visible"
    v-model:visible="visible"
    v-model="state"
    title="创建新角色"
    size="25%"
    :form="{ columns, rules, labelPosition: 'right', labelWidth: 90 }"
    @cancel="handleCancel"
    @confirm="handleConfirm"
  >
    <template #plus-field-description>
      <el-input
        v-model="state.description"
        type="textarea"
        :rows="3"
        placeholder="请输入角色描述"
      />
    </template>
  </PlusDrawerForm>
</template>
